import { Component, ParentProps, createSignal, onMount } from "solid-js";
import Sidebar from "./components/Sidebar";
import "./App.css";
import { SidebarProvider, useIsMobile, useSidebar } from "./components/ui/sidebar";
import TitleBar from "./components/TitleBar";
import { Toaster } from "./components/ui/toast";
import { getMatches } from '@tauri-apps/plugin-cli';
import { useNavigate } from "@solidjs/router";

const App: Component = (props: ParentProps) => {
  const isMobile = useIsMobile();
  const navigate = useNavigate();
  const [shouldRefresh, setShouldRefresh] = createSignal(false);

  const handleRefresh = () => {
    setShouldRefresh(prev => !prev);
  };

  onMount(async () => {
    const matches = await getMatches();

    if(typeof matches.args.spk?.value === 'string')
    {
      if(matches.args.spk.value.startsWith('spk://search/'))
      {
        // 处理 spk://search/ 协议
        const path = matches.args.spk?.value.replace('spk://search/', '');
        navigate(`/search?q=${path}`);
      }else if(matches.args.spk.value.startsWith('spk://'))
      {
        // 处理 spk:// 协议
        const path = matches.args.spk?.value.replace('spk://', '');
        const parts = path.split('/');
        const category = parts[parts.length - 2];
        const pkgname = parts[parts.length - 1];
        navigate(`/app/${category}/${pkgname}`);
      }
    }
  })

  return (
    <div class="app-layout">
      <SidebarProvider>
        {/* 根据刷新状态重新渲染 Sidebar */}
        {shouldRefresh() ? (
          <Sidebar />
        ) : (
          <Sidebar />
        )}
        <div class="flex flex-col w-full">
          <Toaster />
          <TitleBar onRefresh={handleRefresh} isSidebarOpen={!isMobile() && useSidebar().open()} />
          {shouldRefresh() ? (
            <main class="main-content w-full h-[calc(100vh-48px)] mt-12 overflow-y-auto" id="main-content">
              {props.children}
            </main>
          ) : (
            <main class="main-content w-full h-[calc(100vh-48px)] mt-12 overflow-y-auto" id="main-content">
              {props.children}
            </main>
          )}
        </div>
      </SidebarProvider>
    </div>
  );
};

export default App;
